<template>
    <div>
    
    </div>
</template>
<script>
export default {
    data(){
        return {

        }
    },
    mounted(){},
    methods:{
        createPromise(){
            class myPromise{
                //executor 状态改变就执行
                constructor(executor){
                    //初始化状态
                    this.state='pending';
                    // 成功的值
                    this.value = undefined;
                    // 失败的原因
                    this.reason = undefined;
                    // 成功存放的数组
                    this.onResolvedCallbacks = [];
                    // 失败存放法数组
                    this.onRejectedCallbacks = [];
                    //成功执行
                    let resolve=value=>{
                        if(this.state=='pending'){
                            // resolve调用后，state转化为成功态
                            this.state = 'fulfilled';
                            // 储存成功的值
                            this.value = value;
                            // 一旦resolve执行，调用成功数组的函数
                            this.onResolvedCallbacks.forEach(fn=>fn());
                        }
                    };
                    //失败执行
                    let reject=reason=>{
                        if(this.state=='pending'){
                            //状态改变
                            this.state='rejected';
                            //存储改变原因
                            this.reason=reason;
                            // 一旦reject执行，调用失败数组的函数
                            this.onRejectedCallbacks.forEach(fn=>fn());
                        }
                    };
                    try{
                        executor(resolve, reject);
                    } catch (err) {
                        reject(err);
                    }
                }
                //then方法
                then(onFulfilled,onRejected){
                    // 状态为fulfilled，执行onFulfilled，传入成功的值
                    if(this.state=='fulfilled'){
                        onFulfilled(this.value)
                    }
                    // 状态为rejected，执行onRejected，传入失败的原因
                    if(this.state=='rejected'){
                        onRejected(this.reason)
                    }
                    if(this.state=='pending'){
                        this.onResolvedCallbacks.push(()=>{
                            onFulfilled(this.value);
                        })
                        // onRejected传入到失败数组
                        this.onRejectedCallbacks.push(()=>{
                            onRejected(this.reason);
                        })
                    }
                    
                }
            }
        }
    },
}
</script>